﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BugzX.Models;
using BugzX.Repositories;
using DotNetX;
using System.IO;

namespace BugzX.Controllers
{
    public class ProjectController : Controller
    {
        #region Public Methods

        //
        // GET: /Project/
        [Authorize()]
        public ActionResult New()
        {
            return View();
        }

        [Authorize()]
        [HttpPost()]
        public ActionResult New(ProjectViewData p)
        {
            p.Name = p.Name ?? String.Empty;
            p.Name = p.Name.Trim().Replace(' ', '-');
            p.Name = this.Server.UrlEncode(p.Name);

            BugzXDBEntities context = new BugzXDBEntities();
            FormChecker checker = new FormChecker();

            Project newProject = new Project();
            newProject.Name = checker.GetString(p.Name, "Name");
            newProject.OwnerId = UserRepository.GetCurrentUserId();
            newProject.LogoUrl = this.GetProjectFileLogo(checker, p.Name);

            if (!String.IsNullOrEmpty(p.Name))
            {
                if (!ProjectRepository.IsNameUnique(p.Name))
                {
                    checker.AddError(String.Format("The name '{0}' is already in use.", p.Name));
                }
            }

            ProjectComponent pc = new ProjectComponent();
            pc.Name = checker.GetString(p.ComponentName, "Component Name");

            if (checker.HasErrors)
            {
                p.ErrorMessage = checker.ErrorsByBRTag;
                if(!String.IsNullOrEmpty(newProject.LogoUrl))
                    System.IO.File.Delete(this.Server.MapPath(newProject.LogoUrl));

                return this.View(p);
            }
            else
            {
                context.Projects.AddObject(newProject);
                context.SaveChanges();

                pc.ProjectId = newProject.ProjectId;
                context.ProjectComponents.AddObject(pc);
                context.SaveChanges();

                return RedirectToAction(String.Format("/view/{0}", p.Name));
            }
        }

        public ActionResult View(string name)
        {
            var project = ProjectRepository.GetByName(name);
            if (project == null)
                return RedirectToAction("error", "error", new ErrorErrorViewData() { Message = String.Format("The project '{0}' does not exist.", name) });

            var vd = new ProjectViewViewData()
            {
                Name = project.Name
            };

            var components = project.ProjectComponents.OrderByDescending(pc => pc.Bugs.Count).ThenBy(pc => pc.Name);
            foreach (var c in components)
            {
                vd.Components.Add(c);
            }

            return this.View(vd);
        }

        #endregion

        #region Private Methods

        private string GetProjectFileLogo(FormChecker checker, string projectName)
        {
            HttpPostedFileBase file = checker.GetFile(this.HttpContext, "fuLogo", "Logo");

            string url = String.Empty;

            if (file != null && file.ContentLength > 0)
            {
                url = String.Format("/Content/images/ProjectLogos/{0}.png",
                    projectName);

                file.SaveAs(this.Server.MapPath(url));
            }

            return url;
        }

        #endregion
    }
}
